package 机试题16年;

import java.util.Arrays;

/**
 * Created by hest0 on 2017/4/20.
 */
public class 顺时针打印矩阵2 {
    public static void main(String[] args) {
        int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {11, 12, 14, 15}};
        int[] res = new Printer().clockwisePrint(a, a.length, a[0].length);
        System.out.println(Arrays.toString(res));
    }

    public static class Printer {
        public int[] clockwisePrint(int[][] mat, int n, int m) {

            int[] a = new int[n * m];
            int idx = 0;
            int i = 0, j = 0;
            int x1 = 0, x2 = n - 1;
            int y1 = 0, y2 = m - 1;
            while (idx < n * m) {
                //左右行
                for (j = y1, i = x1++; j <= y2; j++)
                    a[idx++] = mat[i][j];
                if (idx >= n * m) break;
                //上下列
                for (i = x1, j = y2--; i <= x2; i++)
                    a[idx++] = mat[i][j];
                if (idx >= n * m) break;
                //右左行
                for (j = y2, i = x2--; j >= y1; j--)
                    a[idx++] = mat[i][j];
                if (idx >= n * m) break;
                //下上列
                for (i = x2, j = y1++; i >= x1; i--)
                    a[idx++] = mat[i][j];
            }
            return a;

        }
    }
}
